package com.da.web.sys_notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.da.common.Result;
import com.da.web.sys_notice.entity.NoticeParm;
import com.da.web.sys_notice.entity.SysNotice;
import com.da.web.sys_notice.service.SysNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author da
 * @time 2023/12/15 下午 12:35
 */
@RestController
@RequestMapping("/api/notice")
public class SysNoticeController {
    @Autowired
    private SysNoticeService sysNoticeService;

    //新增
    @PostMapping
    public Result add(@RequestBody SysNotice sysNotice) {
        //设置创建时间
        sysNotice.setCreateTime(new Date());
        boolean save = sysNoticeService.save(sysNotice);
        if (save) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    //编辑
    @PutMapping
    public Result edit(@RequestBody SysNotice sysNotice) {
        boolean save = sysNoticeService.updateById(sysNotice);
        if (save) {
            return Result.success("编辑成功");
        }
        return Result.error("编辑失败");
    }

    //删除
    @DeleteMapping("/{noticeId}")
    public Result delete(@PathVariable("noticeId") Long noticeId) {
        boolean save = sysNoticeService.removeById(noticeId);
        if (save) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    //列表
    @GetMapping("/list")
    public Result getList(NoticeParm parm) {
        IPage<SysNotice> list = sysNoticeService.pageList(parm);
        return Result.success("查询成功", list);
    }

    //首页公告信息
    @GetMapping("/getTopList")
    public Result getTopList() {
        QueryWrapper<SysNotice> query = new QueryWrapper<>();
        //取最新的3条
        query.lambda().orderByDesc(SysNotice::getCreateTime).last("limit 3");
        List<SysNotice> list = sysNoticeService.list(query);
        return Result.success("查询成功", list);
    }


}
